<?php
class DataModel extends Model {
	//默认图表数据间隔时间
	public $interval = 3600;
	//默认设备字段
	public $field = 'val1';
	//默认数据类型
	public $datatype = 1;
	//风速
	const TYPE_WIND = 1;
	//雨量
	const TYPE_RAIN = 2;
	public $devicetype = array(
		self::TYPE_WIND =>	'风速',
		self::TYPE_RAIN =>	'雨量'
	);
	public $data_convert_coefficient = array(
		self::TYPE_WIND =>	0.03,
		self::TYPE_RAIN =>	0.4
	);
	public function parseFile($file){
		$log = D('Log');

		if(!file_exists($file)){
			$this->error = '文件不存在';
			return false;
		}
		$lines = file_get_contents($file);
		$lines = explode("\n", $lines);

		foreach ($lines as $line) {
			$row = array();
			$val = explode("#", $line);
			$hash = md5(trim($line));
			$row['dateline'] = strtotime($val[0]);
			$row['hash'] = $hash;
			$data = json_decode($val[1], true);
			if(!is_array($data))
				continue;
			$n = 0;
			while($n < 12){
				$row['val' . ($n+1)] = $data[$n];
				$n++;
			}
			$rows[] = $row;
			$count++;
		}

		$success = $this->addAll($rows, array(), true);
		$msg = sprintf($file . " 总共%d条记录, 成功导入%d条记录。", $success, $count);
		$log->log($msg);

		$filemtime = filemtime($file);
		$donedir = dirname($file) . '/done/' . date('Y/m/d/', $filemtime);
		if(!is_dir($donedir)){
			mkDirs($donedir);
		}

		$newfilename = $donedir . $filemtime . '.txt';

		$res = rename($file, $newfilename);
		if(!$res){
			$msg = sprintf("移动文件 %s , 到 %s 发生错误!。", $file, $newfilename);
		}else{
			$msg = sprintf("移动文件 %s , 到 %s 。", $file, $newfilename);
		}
		$log->log($msg);

		return true;
	}
	/**
	*	图表数据间隔时间
	*
	*	@param
	*	@return
	*	@date	2012-9-20
	*	@author lin.x
	*
	*/
	public function setInterval($val){
		$this->interval = $val;
		return $this;
	}
	/**
	*	选取设备
	*
	*	@param
	*	@return
	*	@date	2012-9-20
	*	@author lin.x
	*
	*/
	public function setDevice($n){
		$this->field = 'val' . $n;
		return $this;
	}
	/**
	*	设置图表类型
	*
	*	@param
	*	@return
	*	@date	2012-9-20 17:10
	*	@author lin.x
	*
	*/
	public function setDataType($type){
		$this->datatype = $type;
		return $this;
	}
	/**
	*	选取设备
	*
	*	@param
	*	@return
	*	@date	2012-9-20
	*	@author lin.x
	*
	*/
	public function setName($val){
		$this->name = $val;
		return $this;
	}
	/**
	*	设定图表时间区间
	*
	*	@param
	*	@return
	*	@date	2012-9-20 14:20
	*	@author lin.x
	*
	*/
	public function setTimeRange($starttime, $endtime = 0){
		$starttime = $starttime ? $starttime : time() - 7 * 3600 * 24;
		$this->startime = $starttime;
		$this->endtime = $endtime;
		return $this;
	}
	/**
	*	生成图表数据
	*
	*	@param
	*	@return
	*	@date	2012-9-20 22:44:11
	*	@author lin.x
	*
	*/
	public function getData(){
		$starttime = $this->startime;
		$endtime = $this->endtime;
		$datelineCondition = $endtime ? sprintf(" AND dateline BETWEEN '%s' AND '%s'", $starttime, $endtime) : sprintf(" AND dateline > '%s'", $starttime);

		//最小单位 单位秒
		$unit = $this->interval;

		$sql = sprintf("SELECT sum(`%s`) as val, count(*) as n,  FLOOR(dateline / %d)as ts, dateline FROM __TABLE__ WHERE 1 %s GROUP by ts", $this->field, $unit, $datelineCondition);

		$this->data = $this->query($sql, false);

		$_GET['dump'] && dp($sql, $this->getLastSql(), $res, $this->getError(), $this->getDbError());

		return $this->data;
	}
	/**
	*	生成横坐标数据
	*
	*	@param
	*	@return
	*	@date	2012-9-20 14:19
	*	@author lin.x
	*
	*/
	public function getXcategories(){
		$res = $this->data;
		$interval = $this->interval;
		if($interval >= 24 * 3600){
			$format = 'm-d';
		}elseif($interval >= 3600){
			$format = 'm-d H时';
		}else{
			$format = 'H:i';
		}

		foreach ($res as $val) {
			$data[] = date($format, $val['dateline']);
		}

		return json_encode($data);
	}
	/**
	*	生成y坐标数据
	*
	*	@param
	*	@return
	*	@date	2012-9-20
	*	@author lin.x
	*
	*/
	public function getYseries(){
		$res = $this->data;

		foreach ($res as $val) {
			//仪器到真实数据的转换
			$val['val'] *= $this->data_convert_coefficient[$this->datatype];
			$data[] = floatval(sprintf('%.2f', $val['val']/$val['n']));
			$total += $val['val'];
			$totalcount += $val['n'];
		}

		$avg = floatval(sprintf('%.2f', $total / $totalcount ));

		$respond[] = array(
			'name'	=>	$this->name,
			'data'	=>	$data
		);
		$respond[] = array(
			'name'	=>	'平均值',
			'data'	=>	array_fill(0, count($data), $avg)
		);

		return json_encode($respond);
	}
	/**
	*	生成测试数据
	*
	*	@param
	*	@return
	*	@date	2012-9-18 21:11:11
	*	@author lin.x
	*
	*/
	public function buildTestData($m){
		$n = 0;
		$s = time() - mt_rand(1, 3600 * 24 * 1);
		$m = $m ? $m : mt_rand(100, 1000 * mt_rand(1, 10));
		while($n < $m){
			$s -= mt_rand(10, 100);
			$dateline = date('Y-m-d H:i:s', $s);
			$row = array_fill(0, 12, '');
			$row[0] = mt_rand(50, 200);
			$row[1] = mt_rand(30, 80);
			$row['a'] = '';
			mt_rand(0, 4) === 0 && $row[2] = mt_rand(50, 200);
			mt_rand(0, 4) === 0 && $row[3] = mt_rand(30, 80);
			$line .= $dateline . '#' . json_encode($row) . PHP_EOL;
			$n++;
		}

		$base = C('data_source_dir');
		if(!is_dir($base)){
			die('数据存放目录不存在' . $base);
		}

		$file = $base . date('ymdhis', $s) . '.txt';

		$dir = dirname($file);
		if(!is_dir($dir)){
			mkDirs($dir);
		}
		file_put_contents($file, $line);
		echo 'ok...' . $file;
	}
	/**
	*	分段求和
	*
	*	@param
	*	@return
	*	@date
	*	@author lin.x
	*
	*/
	public function getTotalByRange($range, $type = self::TYPE_WIND){
		$sql = "SELECT '%s' as title, sum(val3) * %f as val1, sum(val4) * %f as val2 FROM __TABLE__ WHERE dateline >= '%d'";
		$f = $this->data_convert_coefficient[$type];
		foreach ($range as $key => $val) {
			$sqls[] = sprintf($sql, $key, $f, $f, $val);
		}
		$sql = sprintf("(%s)", join(") UNION (", $sqls));
		return $this->query($sql, false);
	}
	/**
	*	获取最新值
	*
	*	@param
	*	@return
	*	@date
	*	@author lin.x
	*
	*/
	public function getLastestData($fields){
		return $this->field($fields)->order('dateline DESC')->find();
	}

}